//
//  RichTransactionPicker.m
//  Rich
//
//  Created by Kenny Chen on 2013/12/15.
//  Copyright (c) 2013年 Kenny Chen. All rights reserved.
//

#import "RichTransactionPicker.h"

@interface RichTransactionPicker ()

@end

@implementation RichTransactionPicker

@synthesize sourceTransArray;
@synthesize pickedTransArray;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.tableView.tag = RichTableViewTagTransPicker;
        sourceTransArray = [[NSMutableArray alloc] init];
        pickedTransArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Source Transaction Array

- (void)setSourceTransArray:(NSMutableArray *)source
{
    [sourceTransArray removeAllObjects];
    
    for (RichTransactionGeneral *__trans in source) {
        [sourceTransArray addObject:__trans];
    }
}

- (void)setPickedTransArray:(NSMutableArray *)picked
{
    [pickedTransArray removeAllObjects];
    
    for (RichTransactionGeneral *__trans in picked) {
        [pickedTransArray addObject:__trans];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [sourceTransArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    tableCellStyle = RichTableCellStyleDetail;
    cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    
    RichTransactionGeneral *trans = [sourceTransArray objectAtIndex:[indexPath row]];
    
    if (trans) {
        cell.textLabel.text = [NSString stringWithFormat:@"%@ %@ - %@ %@",
                               [[RichDelegate core] stringFromDate:trans.date format:@"MM/dd"],
                               [[[RichDelegate core] category] objectForKey:[NSNumber numberWithInteger:[[RichDelegate core] rootCategoryOf:trans.categoryCode]]],
                               [[[RichDelegate core] category] objectForKey:[NSNumber numberWithInteger:trans.categoryCode]],
                               trans.installmentPaymentTimes > 1 ?
                                    [NSString stringWithFormat:@"(%lu/%ld)", trans.installmentMade, trans.installmentPaymentTimes] : @""];
        
        if (trans.installmentMade == 1)
            cell.detailTextLabel.text = [NSString stringWithFormat:RichLocaleString(@"$ %d"), trans.installmentDownPayment];
        else {
            float rate = trans.installmentRate;
            
            cell.detailTextLabel.text = [NSString stringWithFormat:RichLocaleString(@"$ %d"),
                                         trans.amount + ((int)(((trans.amount * trans.installmentPaymentTimes)
                                                                - trans.installmentDownPayment) * rate) / 100)];
        }
        
        if ([self isTransactionPicked:trans])
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        else
            cell.accessoryType = UITableViewCellAccessoryNone;
        cell.userInteractionEnabled = YES;
    }
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    RichTransactionGeneral *__trans = [sourceTransArray objectAtIndex:[indexPath row]];
    
    if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryNone) {
        [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
        [pickedTransArray addObject:__trans];
    }
    else {
        [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
        [pickedTransArray removeObject:__trans];
    }
    
    if (self.callerDelegate)
        [self.callerDelegate tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath];
}

#pragma mark - Picked Transaction

- (BOOL)isTransactionPicked:(RichTransactionGeneral *)transaction
{
    for (RichTransactionGeneral *__trans in pickedTransArray) {
        if (transaction.transId == __trans.transId)
            return YES;
    }
    
    return NO;
}

@end
